package org.emergency.framework.serviceImpl.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.emergency.framework.dao.oa.ITbPermissionDAO;
import org.emergency.framework.dao.oa.ITbRoleDAO;
import org.emergency.framework.model.TbPermission;
import org.emergency.framework.model.TbRole;
import org.emergency.framework.service.common.IRolePermissionMapping;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

@Repository(value = "rolePermissionMappingImpl")
public class RolePermissionMappingImpl extends HibernateDaoSupport implements
		IRolePermissionMapping {
	@Resource
	public void setEMSessionFactory(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}
	
	private static Map<String, Collection<TbPermission>> authMap = new HashMap<String, Collection<TbPermission>>();

	@Resource(name="tbRoleDAO")
	private ITbRoleDAO roleDao;
	
	@Resource(name = "tbPermissionDAO")
	private ITbPermissionDAO tbPermissionDAO;
	
	private List<TbPermission> list = new ArrayList<TbPermission>();

	@Override
	public List<TbPermission> queryTbPermissionByRole(String roleId){
		Collection<TbPermission> tbPermissionCollection = authMap.get(roleId);		
		list.clear();
		try {
		for(TbPermission tbp : tbPermissionCollection){
			System.out.println("++++++++++++根据角色ID查询权限：======"+tbp.getPName());
			list.add(tbp);
		}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public void updateMap() {
		authMap.clear();
		System.out.println("++++++++++++重新加载静态map：======");
		loadRolePermission();
	}

	@Override
	public Map<String, Collection<TbPermission>> loadRolePermission() {
		List<TbRole> roleList;
		try {
			roleList = roleDao.findAll();		
		for (TbRole role : roleList) {
			
			String hqlString = "select r.tbPermission from TbRolePermission r where r.tbRole.tbRoleId = "
					+ role.getTbRoleId() + "";
			Collection<TbPermission> authList = tbPermissionDAO
					.getHibernateTemplate().find(hqlString);
			authMap.put(role.getTbRoleId(), authList);
			System.out.println("++++++++++++静态map：======("+role.getName()+","+authList.size()+")");
		}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return authMap;
	}

}
